﻿using System.Text;
using Best.SmartCms.Dto.Response;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Best.SmartCms.API.Filters
{
    /// <summary>
    /// 验证
    /// </summary>
    public class ModelValidationFilter : IActionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
                return;
            var builder = new StringBuilder();
            foreach (var kvp in context.ModelState)
            {
                if (kvp.Value.ValidationState != ModelValidationState.Invalid)
                    continue;
                foreach (var valueError in kvp.Value.Errors)
                {
                    builder.AppendLine(valueError.ErrorMessage);
                }
            }
            var message = builder.ToString().Trim();
            var res = new ApiResponse
            {
                Code = ResponseCode.ParameterError,
                Message = message,
            };

            context.Result = new ObjectResult(res);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }
    }
}
